package com.itheima.service;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    public User selectById(Integer id) {
        //调用UserMapper.selectById()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 调用方法
        User user = mapper.selectById(id);

        sqlSession.close();

        return user;
    }

    public void deleteById(Integer id) {
        //调用UserMapper.deleteById()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 调用方法
        mapper.deleteById(id);

        sqlSession.commit();
        sqlSession.close();
    }

    public List<User> selectByAdminId(Integer adminId) {
        //调用UserMapper.selectByAdminId()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 调用方法
        List<User> users = mapper.selectByAdminId(adminId);

        sqlSession.close();

        return users;
    }

    public void updateStaffPasswordById(Integer id, String password) {
        //调用UserMapper.updateStaffPasswordById()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 调用方法
        mapper.updateStaffPasswordById(id, password);

        sqlSession.commit();
        sqlSession.close();
    }
}
